package net.longjin.controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import net.longjin.annotation.IgnoreAuth;
import net.longjin.annotation.LoginUser;
import net.longjin.entity.UserInfo;
import net.longjin.utils.DICTokenUtil;
import net.longjin.utils.ResResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class LoginController {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @IgnoreAuth
    @PostMapping("/logic")
    public ResResult Logic(@RequestBody JSONObject json, HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(1L);
        userInfo.setNickname("浅唱幸福");
        userInfo.setOrgId("100001");
        userInfo.setRealname("何志鹏");
        userInfo.setPhone("15921363365");
        // 生成token
        String token = DICTokenUtil.createToken(JWT.create().withIssuer("system").withClaim("userId", userInfo.getUserId())
                .withClaim("orgId", userInfo != null ? userInfo.getOrgId() : "")
                .withClaim("name", userInfo.getRealname()).withAudience(userInfo.getNickname()), "token_" + userInfo.getUserId());
        request.setAttribute("userInfo", userInfo);
        response.setHeader("token", token);
        return ResResult.success(userInfo);
    }


    @PostMapping("/getUserInfo")
    public ResResult getUserInfo(@LoginUser UserInfo userInfo) {
        return ResResult.success(userInfo);
    }

    @GetMapping("/testRedis")
    @IgnoreAuth
    public ResResult testRedis() {
        redisTemplate.opsForValue().set("test","何志鹏");
        String test = redisTemplate.opsForValue().get("test");
        return ResResult.success(test);
    }

}
